<template>
  <div class="file-preview">
    <!-- 可预览文件类型 -->
    <el-link
      v-if="showPreviewLink"
      type="primary"
      :underline="true"
      @click="handlePreview"
      class="preview-link"
    >
      {{ enhancedFileName }}
    </el-link>

    <!-- 其他文件类型直接打开 -->
    <el-link
      v-else
      type="primary"
      :underline="true"
      :href="fileSrc"
      target="_blank"
      class="download-link"
    >
      {{ enhancedFileName }}
    </el-link>

    <!-- 预览弹窗（PDF 不使用弹窗） -->
    <el-dialog
      v-if="fileType !== 'pdf'"
      :title="'预览 - ' + enhancedFileName"
      :visible.sync="previewVisible"
      width="80%"
      top="5vh"
      append-to-body
    >
      <div class="preview-content">
        <!-- Word -->
        <iframe
          v-if="['doc', 'docx'].includes(fileType)"
          :src="'https://view.xdocin.com/view?src=' + encodeURIComponent(fileSrc)"
          width="100%"
          height="600px"
          frameborder="0"
        ></iframe>

        <!-- Excel -->
        <iframe
          v-else-if="['xls', 'xlsx'].includes(fileType)"
          :src="'https://view.xdocin.com/view?src=' + encodeURIComponent(fileSrc)"
          width="100%"
          height="600px"
          frameborder="0"
        ></iframe>

        <!-- 图片 -->
        <img
          v-else-if="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileType)"
          :src="fileSrc"
          alt="图片预览"
          style="max-width: 100%; max-height: 80vh;"
        />

        <!-- 文本/代码 -->
        <pre
          v-else-if="['txt', 'csv', 'json', 'xml', 'html', 'js', 'ts', 'java', 'py', 'c', 'cpp', 'css'].includes(fileType)"
          class="text-preview"
        >{{ textContent }}</pre>

        <!-- 音频 -->
        <audio
          v-else-if="['mp3', 'wav', 'ogg'].includes(fileType)"
          :src="fileSrc"
          controls
          style="width: 100%;"
        ></audio>

        <!-- 视频 -->
        <video
          v-else-if="['mp4', 'webm', 'ogv'].includes(fileType)"
          :src="fileSrc"
          controls
          style="max-width: 100%; max-height: 80vh;"
        ></video>

        <!-- 不支持的类型 -->
        <div v-else>
          暂不支持该文件类型的在线预览，请下载后查看。
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
        <!-- 下载按钮 -->
        <a :href="fileSrc" :download="enhancedFileName" target="_blank">
          <el-button type="primary">下载</el-button>
        </a>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEnhancedFileName } from "@/utils/url-dispose";

export default {
  name: "FilePreview",
  props: {
    src: {
      type: String,
      required: true,
      default: ""
    }
  },
  data() {
    return {
      enhancedFileName: "",
      fileType: "",
      previewVisible: false,
      fileSrc: "",
      textContent: ""
    };
  },
  computed: {
    showPreviewLink() {
      return [
        "pdf", "doc", "docx", "xls", "xlsx",
        "jpg", "jpeg", "png", "gif", "bmp", "webp",
        "txt", "csv", "json", "xml", "html", "js", "ts", "java", "py", "c", "cpp", "css",
        "mp3", "wav", "ogg",
        "mp4", "webm", "ogv"
      ].includes(this.fileType);
    }
  },
  watch: {
    src: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.fileSrc = newVal;
          this.parseFileNameAndType(newVal);
        }
      }
    }
  },
  methods: {
    async parseFileNameAndType(url) {
      try {
        this.enhancedFileName = getEnhancedFileName(url);
        const fileName = this.enhancedFileName || "";
        let fileExtension = "";

        if (fileName.includes(".")) {
          fileExtension = fileName.split(".").pop().toLowerCase();
        } else if (url) {
          const urlObj = new URL(url);
          const pathname = urlObj.pathname;
          if (pathname.includes(".")) {
            fileExtension = pathname.split(".").pop().toLowerCase();
          }
        }
        this.fileType = fileExtension;

        // 如果是文本或代码文件，提前加载内容
        if (["txt", "csv", "json", "xml", "html", "js", "ts", "java", "py", "c", "cpp", "css"].includes(fileExtension)) {
          try {
            const res = await fetch(url);
            this.textContent = await res.text();
          } catch (err) {
            console.error("加载文本文件失败:", err);
            this.textContent = "无法加载文件内容";
          }
        }
      } catch (error) {
        console.error("解析文件名或类型出错:", error);
        this.enhancedFileName = "file";
        this.fileType = "";
      }
    },
    handlePreview() {
      if (this.fileType === "pdf") {
        // PDF 直接用浏览器打开
        window.open(this.fileSrc, "_blank");
      } else if (this.showPreviewLink) {
        // 其他类型弹窗预览
        this.previewVisible = true;
      }
    }
  }
};
</script>

<style scoped>
.preview-link,
.download-link {
  cursor: pointer;
}
.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.preview-content iframe {
  width: 100%;
  min-height: 600px;
  border: 1px solid #ddd;
}
.text-preview {
  width: 100%;
  max-height: 80vh;
  overflow: auto;
  background: #f5f5f5;
  padding: 10px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
